package cn.vcjf.weapp.api.user.controller;


import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.web.bind.annotation.ResponseBody;
import cn.vcjf.weapp.common.web.TableResult;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import cn.vcjf.weapp.api.user.entity.ShoppingCar;
import cn.vcjf.weapp.api.user.service.ShoppingCarService;

import org.springframework.stereotype.Controller;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhengzihang
 * @since 2018-09-25
 */
@Controller
@RequestMapping("/user/shoppingCar")
public class ShoppingCarController {
	@Resource
	private ShoppingCarService shoppingCarService;

	/**
	 * 添加购物车
	 *
	 * @param shoppingCar
	 * @return
	 */
	@RequestMapping("/addShoppingCar")
	@ResponseBody
	public TableResult addShoppingCar(@Valid ShoppingCar shoppingCar, BindingResult result) {

		TableResult.checkParams(result);

		shoppingCar.preInsert();
		boolean b = shoppingCarService.insert(shoppingCar);
		return TableResult.Result(b);
	}

	/**
	 * 修改购物车,只能修改数量
	 *
	 * @param shoppingCar
	 * @return
	 */
	@RequestMapping("/updateShoppingCar")
	@ResponseBody
	public TableResult updateShoppingCar(ShoppingCar shoppingCar) {
		ShoppingCar update = new ShoppingCar();
		update.setId(shoppingCar.getId());
		//删除购物车物品
		if(shoppingCar.getGoodsNo() == 0){
			return deleteShoppingCar(update);
		}
		update.setGoodsNo(shoppingCar.getGoodsNo());
		update.preUpdate();
		boolean b = shoppingCarService.updateById(update);
		return TableResult.Result(b);
	}

	/**
	 *
	 *
	 * @param shoppingCar
	 * @return
	 */
	@RequestMapping("/findShoppingCarOne")
	@ResponseBody
	public TableResult findShoppingCarOne(ShoppingCar shoppingCar) {

		EntityWrapper<ShoppingCar> wrapper = new EntityWrapper<ShoppingCar>();

		if (shoppingCar.getId() != null) {
			wrapper.eq("id", shoppingCar.getId());
		}
		//Todo

		ShoppingCar result = shoppingCarService.selectOne(wrapper);

		return TableResult.OKResult(result);
	}

	/**
	 * 查询用户的购物车
	 *
	 * @param shoppingCar
	 * @return
	 */
	@RequestMapping("/findShoppingCarList")
	@ResponseBody
	public TableResult findShoppingCarList(ShoppingCar shoppingCar) {

		EntityWrapper<ShoppingCar> wrapper = new EntityWrapper<ShoppingCar>();

		wrapper.eq("sysUserId", shoppingCar.getSysUserId());
		wrapper.eq("userId", shoppingCar.getUserId());

		Page<ShoppingCar> page = shoppingCar.getPageInfo();

		page = shoppingCarService.selectShoppingCar(page, shoppingCar);

		return TableResult.OKResult(page);

	}

	@RequestMapping("/deleteShoppingCar")
	@ResponseBody
	public TableResult deleteShoppingCar(ShoppingCar shoppingCar) {
		shoppingCar.preUpdate();
		boolean b = shoppingCarService.deleteById(shoppingCar.getId());
		return TableResult.Result(b);
	}

}
